package com.tunan.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.TypeAlias;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.github.pagehelper.PageHelper;


@Configuration(value="mybatisConfig")
@EnableTransactionManagement
@MapperScan(basePackages={"com.tunan.persistence.dao.sck","com.tunan.system.persistence.dao"}, sqlSessionFactoryRef = "sqlSessionFactoryForPrimary")
//@MapperScan(value = "com.*.*.persistence.dao")
public class MyBatisConfig {
	
	@Bean
	@ConfigurationProperties(prefix = "spring.datasource-primary")
	public DataSource primaryDataSource() {
		return DataSourceBuilder.create().build();
	}
	
	@Bean
	public JdbcTemplate getJdbcTemplate() {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(primaryDataSource());
		return jdbcTemplate;
	}
	
	@Bean
	public SqlSessionFactory sqlSessionFactoryForPrimary() throws Exception {
		SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
		ssfb.setDataSource(primaryDataSource());
		
		//分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("dialect", "mysql");
        properties.setProperty("reasonable", "true");
        pageHelper.setProperties(properties);
        //添加插件
        ssfb.setPlugins(new Interceptor[]{pageHelper});
		
		return ssfb.getObject();
	}	
	
	@Bean
    public DataSourceTransactionManager transactionManagerForPrimary() {  
        return new DataSourceTransactionManager(primaryDataSource());  
    } 

	
}
